/**
* 售票页面
*/
import React, { Component } from 'react'

import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  Dimensions,
  TouchableOpacity,
  StatusBar,
  Modal,
  ScrollView
} from 'react-native'

import GetSetStorge from '../../common/GetSetStorge'
import FetchResources from '../../common/FetchResources'
import { RouteHelper } from 'react-navigation-easy-helper'
import NavPage from '../../common/NavPage'
import Screen from '../../common/screen'
import axios from 'axios'
import qs from 'qs'
import screen from '../../common/screen';
import { Geolocation } from 'react-native-baidu-map'
import BackgroundTimer from 'react-native-background-timer'
import moment from 'moment'

export default class Customer extends Component {
  static navigationOptions = ({ navigation }) => ({
    tabBarOnPress: (tab) => {
      navigation.state.params.navigatePress()
      tab.jumpToIndex(tab.scene.index)
    }
  })

  constructor(props) {
    super(props)
    this.state = {
      consumptionName: '',
      consumptionId: '',
      price: '',
      TicketVerify: true,
      permissionList: [],
      inspectDataList: [],
      ticketTitle: '',
      inspectList: false,
      inspect: false,
      sellTicket: true,
      locationArr: [],
      modalVisible: false,
      ip: '192.168.70.147:8080',
      newIp: '192.168.70.147:8080'
    }
  }


  componentDidMount() {
    GetSetStorge.getStorgeAsync('ip').then(ip => {
      if (ip) {
        this.setState({ ip })
      }
    })
    this.intervalId = BackgroundTimer.setInterval(() => {
      this.getLocation()
    }, 2000)
    RouteHelper.navigate('TicketVerify')
    //已登录状态，再次进去时查询该账户关联的项目及价格
    GetSetStorge.getStorgeAsync('loginInfo').then((result) => {
      if (result) {
        axios.post(FetchResources.Fetch.GetPermission,//获取当天权限和项目价格
          qs.stringify({
            sellerId: result.split('|')[0],
          })
        ).then((response) => {
          if (response.data.success) {//查询成功
            let permissionList = response.data.permissionList

          }
        }).catch((error) => {
        })
      }
    }).catch((error) => {
      console.log('==========================')
      console.log('系统异常' + error)
      console.log('==========================')
    })

    this.props.navigation.setParams({ navigatePress: this.clickTabCallback })
  }

  componentWillUnmount() {
    BackgroundTimer.clearInterval(this.intervalId)
  }

  getLocation() {
    Geolocation.getCurrentPosition()
      .then(data => {
        let { latitude, longitude } = data
        let location = `${moment(new Date()).format('YYYY-MM-DD hh:mm:ss')},lat: ${latitude}, lon: ${longitude}, ip: ${this.state.ip}`
        GetSetStorge.getStorgeAsync('loginInfo').then(userId => {
          axios.post(`http://${this.state.ip}/app/gps/sendGis.do`,
            qs.stringify({
              // deviceId: userId.split('|')[0],
              deviceId: '00001',
              pointLon: longitude,
              pointLat: latitude
            })
          ).then(response => {

          }).catch(error => {

          })
        })

        let newLocationArr = this.state.locationArr
        if (newLocationArr.length > 40) {
          newLocationArr.splice(0, 39)
        } else {
          newLocationArr.push(location)
        }
        this.setState({
          locationArr: newLocationArr
        })
      })
  }

  // tab 切换调用方法
  clickTabCallback = () => {
    // this.refs.header.reload()
  }

  onButtonPress(consumptionName, consumptionId, price) {

  }

  goBack() {
    RouteHelper.pop()
  }

  closeModel = () => {
    this.setState({ modalVisible: false })
  }

  submit = () => {
    this.closeModel()
    GetSetStorge.setStorgeAsync('ip', this.state.newIp)
    this.setState({ ip: this.state.newIp })
  }

  render() {
    const bgText = ['#4DC6ED', '#F0576F', '#D35FC4', '#FFA898', '#5D90EA']
    let { permissionList, consumptionId, consumptionName, price, TicketVerify, ticketTitle, sellTicket, inspectList, inspect, locationArr } = this.state
    return (
      <View style={{ flex: 1 }} >
        <StatusBar
          animated={true}
          hidden={false}
          backgroundColor={'#5C7094'}
          translucent={true}
          barStyle={'light-content'}
          showHideTransition={'fade'}
          networkActivityIndicatorVisible={true}
        />
        <NavPage goBack={() => { RouteHelper.pop() }} showGoBack={''} title={'GPS定位记录'} refund={''} showInspect={inspectList} bgColor={'#F6F7F8'} />
        <View style={styles.container}>
          <View style={{ height: 30 }}>
            <Text style={{ fontSize: 20, fontWeight: '500', color: '#111', marginLeft: Screen.width * 0.075 }}>{ticketTitle}</Text>
          </View>
          <TouchableOpacity onPress={() => this.setState({ modalVisible: true })} style={{ flexDirection: 'row', justifyContent: 'center' }}><Image style={styles.icon} source={require('../../img/settings.png')} /><Text>点击设置服务器ip和端口</Text></TouchableOpacity>
          <ScrollView
            showsVerticalScrollIndicator={false}    // 隐藏垂直指示器
            style={{ flex: 1 }}
          >
            <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'center', width: Screen.width, paddingTop: 10, }}>
              {
                locationArr.length > 0 && locationArr.map(item => (
                  <Text>{item}</Text>
                ))
              }
            </View>
          </ScrollView>
        </View>
        <Modal
          animationType="fade"
          transparent={false}
          visible={this.state.modalVisible}
        >
          <View style={{ alignItems: 'center' }}>
            <Text style={{ marginTop: 30, fontSize: 18 }}>请填写服务器ip和端口</Text>
            <View style={{ height: 200, width: screen.width }}>
              <TextInput
                placeholder="127.0.0.1:8080"
                underlineColorAndroid="transparent"
                returnKeyType={'send'}
                onSubmitEditing={() => this.submit}
                placeholderTextColor='#ccc'
                style={styles.txt}
                defaultValue={this.state.ip}
                onChangeText={newIp => this.setState({ newIp })}
              />
            </View>
            <View style={{ flexDirection: 'row', alignItems: 'center' }}>
              <Text style={{ width: screen.width / 2 - 15, textAlign: 'center', textAlignVertical: 'center', borderRadius: 10, marginHorizontal: 5, fontSize: 18, height: 45, backgroundColor: '#eeeeee', color: '#fff' }} onPress={this.closeModel}>取消</Text>
              <Text style={{ width: screen.width / 2 - 15, textAlign: 'center', textAlignVertical: 'center', borderRadius: 10, marginHorizontal: 5, fontSize: 18, height: 45, backgroundColor: '#105eae', color: '#fff' }} onPress={this.submit}>确定</Text>
            </View>
          </View>
        </Modal>
      </View >
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F6F7F8',
  },
  header: {
    height: 500
  },
  icon: {
    width: 21,
    height: 21
  },
  item: {
    width: screen.width * 0.9,
    height: screen.width * 0.37,
    marginBottom: 10,
    borderRadius: 5,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row'
  },
  customerImage: {
    flex: 1.5,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  customerImageSize: {
    height: 102,
    width: 132,
    resizeMode: "contain"
  },
  bottomButton: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'flex-end',
    marginBottom: 25,
  },
  TouchableHighlightStyle: {
    borderRadius: 6,
    marginTop: 5,
    padding: 13,
    alignItems: 'center',
    width: Dimensions.get('window').width * 0.85,
    backgroundColor: "#105eae"
  },
  buttonText: {
    fontSize: 16,
    alignItems: 'center',
    textAlign: "center",
    color: "#fff"
  },
  itemNameLay: {
    alignSelf: 'flex-start',
    marginTop: 16,
    paddingHorizontal: Screen.width * 0.088,
  },
  itemName: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#000'
  },
  mainLay: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  inputLay: {
    width: Screen.width * 0.784,
    height: 42,
    marginTop: 16,
    paddingHorizontal: 16,
    borderRadius: 21,
    borderColor: '#CDD5DC',
    borderWidth: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: 'white'
  },
  inputTxt: {
    height: 24,
    padding: 0,
    fontSize: 16,
    flex: 1
  },
  inputCode: {
    width: 24,
    height: 24
  },
  //详情
  detail: {
    width: Screen.width * 0.866,
    height: 224,
    marginTop: 14,
    backgroundColor: 'white',
    borderRadius: 5,
    alignItems: 'center',
    //设置阴影
    shadowOffset: { width: 0, height: 0 },
    shadowColor: 'black',
    shadowOpacity: 1,
    shadowRadius: 5
  },
  theme: {
    marginVertical: 26,
  },
  themeName: {
    fontSize: 16,
    color: 'rgba(0,0,0,.72)',
  },
  itemLay: {
    width: Screen.width * 0.717,
    height: 30,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  itemFs: {
    fontSize: 14,
    color: 'rgba(0,0,0,.42)'
  },
  detailItem: {
    width: Screen.width * 0.866,
    height: 32,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 24,
    paddingLeft: Screen.width * 0.085,
    paddingRight: Screen.width * 0.0426,
    borderTopColor: '#CDD5DC',
    borderTopWidth: 1,

  },
  itemTxt: {
    fontSize: 14,
    color: 'rgba(0,0,0,.72)',
  },
  txt: {
    width: screen.width * 0.8,
    alignSelf: 'center',
    height: 40,
    fontSize: 15,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: '#105eae',
    marginTop: 80,
  }
});